import React, {useContext, useEffect, useRef, useState} from 'react'
import moment from 'moment'
import {
	Button,
	Form,
	Input,
	Popconfirm,
	Table,
	Select,
	Pagination,
	message,
} from 'antd'
import type {FormInstance} from 'antd/es/form'
import {ArrowDownOutlined} from '@ant-design/icons'
import {getKeyValueByType, getRecordList} from '@/service/merchantCenter/clue'
import {PageType} from '../constant'
import Styles from './index.less'
import {getDict} from '@/service/common/dict'
import {downloadDocumentUrl} from '@/service/common/download'

const {TextArea} = Input

const EditableContext = React.createContext<FormInstance<any> | null>(null)

// interface Item {
//   key: string;
//   name: string;
//   age: string;
//   address: string;
// }

interface EditableRowProps {
	index: number
}

// eslint-disable-next-line react/function-component-definition
const EditableRow: React.FC<EditableRowProps> = ({...props}) => {
	const [form] = Form.useForm()
	return (
		<Form form={form} component={false}>
			<EditableContext.Provider value={form}>
				<tr {...props} />
			</EditableContext.Provider>
		</Form>
	)
}

// eslint-disable-next-line react/function-component-definition
const EditableCell: React.FC<any> = ({
	title,
	editable,
	children,
	dataIndex,
	record,
	handleSave,
	keysList,
	allKeysList,
	...restProps
}) => {
	// const [editing, setEditing] = useState(false);
	const ref = useRef<any>(null)
	const form = useContext(EditableContext)!

	// useEffect(() => {
	//   if (editing) {
	//     ref.current!.focus();
	//   }
	// }, [editing]);
	// 列输入内容改变
	const save = async () => {
		try {
			const values = await form.validateFields()
			// toggleEdit();
			handleSave({...record, ...values})
		} catch (errInfo) {
			/* empty */
		}
	}
	// 列表状态选项改变
	const savechange = async (e: any) => {
		try {
			const values = await form.validateFields()
			// toggleEdit();
			handleSave({...record, ...values})
		} catch (errInfo) {
			/* empty */
		}
		const list1: any = []
		keysList?.forEach((item1: any) => {
			if (Number(item1?.value) > e) {
				list1.push(item1)
			}
		})
	}

	let childNode = children

	// if(record?.key){
	//   const num =
	// }
	if (editable && dataIndex === 'traceStatus') {
		childNode =
			record?.[dataIndex] === 8 ? (
				<>
					{allKeysList?.map(
						(item: {value: string; valueName: string}) => {
							if (item?.value === '8') {
								return item?.valueName
							}
							return ''
						},
					)}
				</>
			) : (
				<Form.Item
					style={{margin: 0}}
					name={dataIndex}
					rules={[
						{
							required: true,
							message: `请选择线索跟进状态`,
						},
					]}>
					<Select
						defaultValue={record[dataIndex]?.toString()}
						placeholder="请选择"
						onChange={savechange}
						ref={ref}
						disabled={!record.edit}
						fieldNames={{label: 'valueName', value: 'value'}}
						options={keysList}
					/>
				</Form.Item>
			)
	}
	if (editable && dataIndex === 'description') {
		childNode = (
			<Form.Item
				style={{margin: 0}}
				name={dataIndex}
				rules={[
					{
						required: true,
						message: `只允许输入200字`,
						max: 200,
					},
				]}>
				<TextArea
					defaultValue={record[dataIndex]}
					onPressEnter={save}
					onBlur={save}
					disabled={!record.edit}
				/>
			</Form.Item>
		)
	}

	return <td {...restProps}>{childNode}</td>
}

type EditableTableProps = Parameters<typeof Table>[0]

interface DataType {
	key: React.Key
	name: string
	age: string
	address: string
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>

// eslint-disable-next-line react/function-component-definition
const AccordingToRecords = ({
	pageType,
	// detailRecord,
	clueId,
	setAccordingToRecordsValue,
	name,
	status,
	followPerson,
	referrerForm,
}: any) => {
	// const disabled = pageType === 'detail'

	const [tableList, setTableList] = useState<any[]>([])

	const [total, setTotal] = useState(0)

	const [maxNum, setMaxNUM] = useState(0)

	const [formData, setFormData] = useState({})

	const [loading, setLoading] = useState(false)

	const [nameValue, setNameValue] = useState('')

	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [dict, setDict] = useState({
		Follow_Status: [], // 线索跟进状态
	})
	const [keysList, setKeysList] = useState([])
	const [allKeysList, setAllKeysList] = useState([])
	const getKeysFun = () => {
		getKeyValueByType({type: 'Follow_Status'}).then((res: any) => {
			if (res.data) {
				setAllKeysList(res?.data)
				const list: any = [...res.data]
				// 删除不可选的数值
				list.forEach((item: any, index: any) => {
					if (item.value === '0') {
						list.splice(index, 1)
					}
					if (item.value === '1') {
						list.splice(index, 1)
					}
					if (item.value === '8') {
						list.splice(index, 1)
					}
				})
				const list1: any = []
				// 删除已经走过的状态
				list?.forEach((res1: any) => {
					list1.push({
						...res1,
						disabled: Number(res1.value) <= status,
					})
				})
				setKeysList(list1)
			}
		})
	}

	useEffect(() => {
		if (keysList.length === 0) {
			getKeysFun()
		}
		setNameValue(name)
	}, [name])
	useEffect(() => {
		const newTableList = [...tableList]
		const max = newTableList?.[0]?.traceStatus
		if (max) {
			const list1: any = []
			// 删除已经走过的状态
			keysList?.forEach((res1: any) => {
				list1.push({
					...res1,
					disabled: Number(res1.value) <= max,
				})
			})
			setKeysList(list1)
		}
	}, [tableList])
	const getTabelValue = async (value: any, pagination?: any) => {
		setLoading(true)
		let values = value
		setFormData(values)
		const newPagination = pagination || {
			current: 1,
			size: params.size,
		}

		setParams(newPagination)
		values = {
			...values,
			...newPagination,
		}
		const res = await getRecordList({...values, clueId})
		if (res?.data) {
			if (!maxNum) {
				setMaxNUM(res.data?.total)
			}
			setTotal(res.data?.total || 0)
			if (res.data?.records) {
				const newData = res.data?.records?.map((item: any) => ({
					...item,
					key: item?.id,
				}))
				setTableList(newData || [])
			}
		}
		setLoading(false)
	}

	useEffect(() => {
		getTabelValue(formData)
		getDict(
			{
				dictKeys: ['Follow_Status'],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	const handleDelete = (key: React.Key) => {
		const newData = tableList.filter((item) => item.key !== key)
		setTableList(newData)
	}

	const defaultColumns: any = [
		{
			title: '线索跟进BD',
			dataIndex: 'userName',
			align: 'center',
			width: 100,
		},
		{
			title: '推荐人',
			dataIndex: 'referrerName',
			align: 'center',
			width: 100,
		},
		{
			title: '跟进时间',
			dataIndex: 'followTime',
			align: 'center',
			width: 200,
		},
		{
			title: '线索跟进状态',
			dataIndex: 'traceStatus',
			align: 'center',
			width: 100,
			editable: true,
			ab: 1,
			render: (text: string) => (
				<>
					{dict.Follow_Status?.map(
						(item: {dictKey: string; dictValue: any}) => {
							if (item?.dictKey === text?.toString()) {
								return <span>{item?.dictValue}</span>
							}
							return null
						},
					)}
				</>
			),
		},
		{
			title: '跟进结果录入',
			dataIndex: 'description',
			align: 'center',
			editable: true,
		},
		{
			title: '操作',
			dataIndex: 'operation',
			render: (text: any, record: any) => {
				if (!record.createTime) {
					return (
						<Popconfirm
							title="确定删除?"
							onConfirm={() => handleDelete(record.key)}>
							<Button type="link">删除</Button>
						</Popconfirm>
					)
				}
				return <></>
			},
		},
	]

	const handleAdd = () => {
		if (nameValue) {
			if (tableList?.[0]?.traceStatus) {
				const referrerValue = referrerForm?.getFieldsValue()
				const newData: any = {
					key: total,
					clueId,
					userName: nameValue,
					uId: followPerson,
					referrerName:
						referrerValue?.newUserName ||
						referrerValue?.existUserName,
					followTime: moment().format('YYYY-MM-DD HH:mm:ss'),
					edit: true,
				}
				const newDatas: any[] = [...tableList]
				newDatas.unshift(newData)
				setTableList(newDatas)
				setTotal(total + 1)
			} else {
				message.warning('一次只能新增一条')
			}
		} else {
			message.warning('请先选择跟进人')
		}
	}

	const handleSave = (row: DataType) => {
		const newData = [...tableList]
		const index = newData.findIndex((item) => row.key === item.key)
		const item = newData[index]
		newData.splice(index, 1, {
			...item,
			...row,
		})
		const propsData = newData.slice(0, newData.length - maxNum)

		setAccordingToRecordsValue(propsData)
		setTableList(newData)
	}

	const paginationChange = (current: number, size: number) => {
		getTabelValue(formData, {
			current,
			size,
		})
	}

	const components = {
		body: {
			row: EditableRow,
			cell: EditableCell,
		},
	}

	const columns = defaultColumns.map((col: any) => {
		if (!col.editable) {
			return col
		}
		return {
			...col,
			onCell: (record: DataType) => ({
				record,
				editable: col.editable,
				dataIndex: col.dataIndex,
				title: col.title,
				handleSave,
				keysList,
				allKeysList,
			}),
		}
	})
	return (
		<>
			{pageType ? (
				<div className={Styles.accordingToRecords}>
					<div className={Styles.titleBox}>跟进记录</div>
					<div className={Styles.content}>
						{pageType !== PageType.Detail && (
							<div className={Styles.btnList}>
								<Button
									type="primary"
									size="small"
									onClick={() => handleAdd()}>
									新增跟进记录
								</Button>

								<Button
									icon={<ArrowDownOutlined />}
									size="small"
									onClick={() => {
										downloadDocumentUrl({
											resourceId: '180',
											queryDesc:
												'线索跟进记录导出,resourceId:180',
											queryParam: {clueId},
										})
									}}>
									导出
								</Button>
							</div>
						)}
						<div>
							<Table
								components={components}
								// rowClassName={() => 'editable-row'}
								bordered
								loading={loading}
								dataSource={tableList}
								columns={columns as ColumnTypes}
								pagination={false}
							/>
							<div
								style={{
									paddingTop: '12px',
									display: 'flex',
									justifyContent: 'end',
								}}>
								<Pagination
									defaultCurrent={1}
									current={params.current}
									total={total}
									// eslint-disable-next-line no-shadow
									showTotal={(total, range) =>
										`第  ${range[0]} - ${range[1]} 条 / 总共 ${total} 条`
									}
									showSizeChanger
									showQuickJumper
									onChange={paginationChange}
								/>
							</div>
						</div>
					</div>
				</div>
			) : (
				<></>
			)}
		</>
	)
}
//
export default AccordingToRecords
